<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-row>
        <el-col :span="14">
          <el-button class="filter-item" size="small" style="margin-left: 10px;" type="primary" v-waves
                     @click="addFunc" icon="el-icon-edit">新增
          </el-button>
          <el-button class="filter-item" size="small" style="margin-left: 10px;" type="primary" v-waves
                     @click="importData" icon="el-icon-upload2">导入
          </el-button>
          <el-button type="primary" :loading="downloadLoading" icon="el-icon-download" @click="exportExcel">导出</el-button>
          <el-button type="primary" @click="downloadTemplateExcel">下载模板</el-button>
        </el-col>
        <el-col :span="10" style="text-align: right">
          <el-input size="small" style="width: 200px" class="filter-item fsc-search" placeholder="车架号"
                    v-model="listQuery.condition.vin" @keyup.enter.native="searchClick"></el-input>
          <!--搜索-->
          <el-button class="filter-item" size="small" type="primary" v-waves icon="el-icon-circle-plus-outline"
                     @click="moreSearch">更多
          </el-button>
          <el-dropdown trigger="click" :hide-on-click=false style="float: right;margin-left: 10px">
            <span class="el-dropdown-link">
              <el-button class="filter-item" size="small" type="primary" v-waves>
                选择列
                <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <el-checkbox-group v-model="theadCheckVal">
                  <el-checkbox label="vin">车架号</el-checkbox>
                  <el-checkbox label="storeHouseId">仓库id</el-checkbox>
                  <el-checkbox label="locationNo">库位名称</el-checkbox>
                  <el-checkbox label="prepareStatus">状态</el-checkbox>
                  <el-checkbox label="materielId">车型</el-checkbox>
                  <el-checkbox label="inboundUser">入库用户</el-checkbox>
                  <el-checkbox label="inboundTime">入库时间</el-checkbox>
                  <el-checkbox label="storeHouseName">仓库名称</el-checkbox>
                </el-checkbox-group>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
      </el-row>
      <div style="clean:both"></div>
    </div>
    <div v-show="searchFlag" style="height: auto;margin-top: 10px;">
      <el-form ref="form" :model="listQuery.condition" label-width="100px" :inline="true">
        <el-form-item label=车架号:>
          <el-input type="textarea" :rows="2" style="width: 250px"
                    v-model="listQuery.condition.vin"  placeholder="请输入车架号, 以逗号来分隔"></el-input>
        </el-form-item>
        <!--<el-form-item label="车型:">-->
          <!--<el-input placeholder="请输入车型名称" class="w200" clearable v-model="listQuery.condition.materielId"></el-input>-->
        <!--</el-form-item>-->
        <el-form-item label="无单入库时间:">
          <el-date-picker class="w200" v-model="listQuery.condition.startDate" type="datetime" placeholder="选择日期时间"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          align="right" ></el-date-picker>
          <span class="zhi-font">至</span>
          <el-date-picker class="w200" v-model="listQuery.condition.endDate" type="datetime" placeholder="选择日期时间"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          align="right" ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search" style="margin-left: 10px">查询</el-button>
          <el-button type="primary" @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div style="clean:both"></div>
    <!--主列表-->
    <el-table ref="paymentTable" :data="tableData" v-loading="listLoading"
              element-loading-text="加载中" border fit highlight-current-row
              style="width: 100%;margin-top:5px" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40"></el-table-column>
      <el-table-column align="center" label="id" v-if="false" width="0">
        <template slot-scope="scope">
          <span>{{scope.row.stockId}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="序号" width="50" fixed="left">
        <template slot-scope="scope">
          <span>{{scope.$index + 1}}</span>
        </template>
      </el-table-column>

      <el-table-column :key="key" align="center" :width="value.width" v-for='(value,key) in tableThead'
                       :label="value.title">
        <template slot-scope="scope">
          <div v-if="value.key === 'prepareStatus'">{{scope.row[value.key] | prepareStatusFilter}}</div>
          <div v-else>{{scope.row[value.key]}}</div>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page.sync="listQuery.current" :page-sizes="[10,20,30,50]" :page-size="listQuery.size"
                     layout="total, sizes, prev, pager, next, jumper" :total="listQuery.total">
      </el-pagination>
    </div>
    <!--导入弹窗-->
    <el-dialog title="无单入库导入" :visible.sync="importDialogVisible" width="75%" :before-close="handleClose">
      <upload-excel-component @on-selected-file='selected'></upload-excel-component>
      <el-button @click="importDialogVisible = false">取 消</el-button>
      <el-button class="filter-item" size="small" style="margin-left: 10px;" type="primary"
                 v-waves icon="el-icon-upload2" @click="confirmImport" :disabled="importLoading">导入</el-button>
      <el-table :data="tableData2" border highlight-current-row style="width: 100%;margin-top:20px;">
        <el-table-column v-for="item in tableHeader" :prop="item" :label="item" :key='item ' :show-overflow-tooltip="true"></el-table-column>
      </el-table>
    </el-dialog>
    <!--新增面板-->
    <store-edit
      :edit_flag="editFlag"
      :edit_main_title="editMainTitle"
      :edit_select_row="editRowData"
      ref="storeEditRef"
      @edit-confirm="editConfirm"
      @edit-close="editClose"
    ></store-edit>
  </div>
</template>
<script>
import * as FactoryPreparationAPI from '@/api/factoryPreparation/factoryPreparation'
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import waves from '@/directive/waves' // 水波纹指令
import * as Utils from '@/utils/index'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import StoreEdit from './fpInBoundConfig/storeEdit'
const defautlTableThead = [
  { key: 'vin', title: '车架号', width: '180' },
  { key: 'storeHouseId', title: '仓库id', width: '120' },
  { key: 'locationNo', title: '库位名称', width: '120' },
  { key: 'prepareStatus', title: '状态', width: '120' },
  // { key: 'stockProperty', title: ' 库存属性', width: '120' },
  // { key: 'qty', title: '库存量', width: '120' },
  { key: 'inboundUser', title: '入库用户', width: 180 },
  { key: 'inboundTime', title: '入库时间', width: '' },
  { key: 'gmtCreated', title: '创建时间', width: '' },
  { key: 'storeHouseName', title: '仓库名称', width: '120' }
]
// const aa1Url = require('static/excel/aa1.xlsx')
export default {
  components: { UploadExcelComponent, StoreEdit },
  name: 'stockQuery',
  directives: { waves },
  data() {
    return {
      theadCheckVal: [
        'vin',
        'storeHouseId',
        'locationNo',
        'prepareStatus',
        'inboundUser',
        'inboundTime',
        'gmtCreated',
        'storeHouseName'
      ],
      tableThead: defautlTableThead,
      listQuery: {
        current: 1,
        size: 10,
        total: 0,
        condition: {
          vin: null,
          queryType: 'Y',
          storeHouseName: null,
          startDate: Utils.parseTime(new Date().getTime(), '{y}-{m}-{d} 00:00:00'),
          endDate: Utils.parseTime(new Date().getTime(), '{y}-{m}-{d} 23:59:59')
        }
      },
      tableData: [],
      listLoading: true,
      searchFlag: true,
      multipleSelection: [],
      importDialogVisible: false, // 导入面板 显示隐藏
      importLoading: false, // 导入
      tableData2: [], // 导入
      tableHeader: [], // 导入
      editFlag: false, // 编辑面板 显示
      editRowData: {}, // 传入 编辑面板 的当前列
      editMainTitle: '', // 编辑面板 标题
      tHeader: [], // 导出 excel头
      filterVal: [], //  导出 excel字段
      filename: '无单车入库列表', // 导出  excel表名
      downloadLoading: false
    }
  },
  created() {
    this.getList()
    this.initFunc()
    // this.getHouseList()
  },
  watch: {
    theadCheckVal(valArr) {
      this.tableThead = defautlTableThead.filter(v => {
        for (let i = 0; i < valArr.length; i++) {
          if (v.key === valArr[i]) {
            return v
          }
        }
      })
    }
  },
  methods: {
    initFunc() {
      this.tHeader = []
      this.filterVal = []
      defautlTableThead.map((item) => {
        this.tHeader.push(item.title)
        this.filterVal.push(item.key)
      })
    },
    changeStatus() {
      return this.downloadData.map(v => {
        if (v.prepareStatus === '10') {
          v.prepareStatus = '工厂未备料入库'
        } else if (v.prepareStatus === '20') {
          v.prepareStatus = '移实顺'
        } else if (v.prepareStatus === '30') {
          v.prepareStatus = '提车指令出库'
        } else if (v.prepareStatus === '40') {
          v.prepareStatus = '返工厂'
        }
        return v
      })
    },
    exportExcel() {
      const that = this
      // 数据导出
      const queryParam = that.listQuery.condition
      queryParam.houseId = that.$store.getters.currentStorehouse.id
      queryParam.queryType = 'N'
      that.downloadLoading = true
      console.log('that.listQuery', queryParam)
      FactoryPreparationAPI.queryFactoryInbound({ condition: queryParam }).then(result => {
        that.downloadLoading = false
        if (result.code === 0) {
          that.downloadData = result.data.records
          if (that.downloadData.length) {
            const arr = that.changeStatus()
            require.ensure([], () => {
              const data = that.formatJson(that.filterVal, arr)
              export_json_to_excel(that.tHeader, data, that.filename)
            })
          }
        } else {
          that.$message({
            title: '信息提示',
            message: result.message,
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    // 新增面板打开
    addFunc() {
      this.editMainTitle = '新增'
      this.editFlag = true
    },
    editConfirm() {
      this.editFlag = false
      this.getList()
    },
    editClose() {
      this.editFlag = false
    },
    // 下载模板
    downloadTemplateExcel() {
      const url = '../../../static/excel/无单车入库导入模板.xlsx'
      const name = '无单车入库导入模板'
      const nowA = document.createElement('a')
      nowA.setAttribute('href', url)
      nowA.setAttribute('download', name)
      nowA.style.display = 'none'
      document.body.appendChild(nowA)
      nowA.click()
      document.body.removeChild(nowA)
    },
    // 打开导入面板
    importData() {
      this.importDialogVisible = true
    },
    // 确定导入  转换列名字
    confirmImport() {
      const data = {
        storeHouseId: this.$store.getters.currentStorehouse.id,
        header: this.tableHeader,
        rows: this.tableData2
      }
      this.importLoading = true
      FactoryPreparationAPI.importPrepareInbound(data).then(result => {
        if (result.code === 0) {
          this.tableHeader = result.data.header
          this.tableData2 = result.data.rows
        } else {
          this.$message({
            title: '错误提示',
            message: result.message,
            type: 'error',
            duration: 2000
          })
        }
        this.importLoading = false
      })
    },
    // 关闭导入面板
    handleClose() {
      this.importDialogVisible = false
      this.tableData2 = []
      this.tableHeader = []
      this.getList()
    },
    // 选择导入
    selected(data) {
      this.tableData2 = data.results
      this.tableHeader = data.header
    },
    // 列表查询
    getList() {
      this.listLoading = true
      // 处理是否展开更多
      let queryParam = {}
      if (this.searchFlag) {
        this.listQuery.condition.storeHouseId = this.$store.getters.currentStorehouse.id
        queryParam = this.listQuery
      } else {
        Object.assign(queryParam, this.listQuery)
        queryParam.condition = {
          startDate: Utils.parseTime(new Date().getTime(), '{y}-{m}-{d} 00:00:00'),
          endDate: Utils.parseTime(new Date().getTime(), '{y}-{m}-{d} 23:59:59'),
          vin: this.listQuery.condition.vin,
          storeHouseName: this.listQuery.condition.storeHouseName,
          storeHouseId: this.$store.getters.currentStorehouse.id
        }
      }
      queryParam.condition.queryType = 'Y'
      FactoryPreparationAPI.queryFactoryInbound(queryParam).then(result => {
        if (result.code === 0) {
          this.tableData = result.data.records
          this.listQuery.total = result.data.total
        } else {
          this.$message({
            title: '信息提示',
            message: result.message,
            type: 'error',
            duration: 2000
          })
        }
        this.listLoading = false
      })
    },
    // 更多
    moreSearch() {
      this.searchFlag = !this.searchFlag
    },
    // 查询
    search() {
      this.listQuery.current = 1
      this.listQuery.size = 10
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.size = val
      this.listQuery.current = 1
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.current = val
      this.getList()
    },
    // 重置
    resetSearch() {
      this.listQuery.current = 1
      this.listQuery.size = 10
      this.listQuery.condition = {
        vin: null,
        storeHouseName: null,
        startDate: Utils.parseTime(new Date().getTime(), '{y}-{m}-{d} 00:00:00'),
        endDate: Utils.parseTime(new Date().getTime(), '{y}-{m}-{d} 23:59:59')
      }
      this.getList()
    },
    // 检查是否选择单条
    checkSelect(data) {
      const l = data.length
      if (l === 0) {
        this.$message({
          message: '未选择',
          type: 'warning',
          duration: 2000
        })
        return false
      }
      return true
    },
    // 表格改变时
    handleSelectionChange(val) {
      this.multipleSelection = val
    }
  }
}
</script>

